import axios from 'axios'
import { ContentType } from '@/api/global.ts'

export const apiGet = <T = any>(url: string, params: object = {}): Promise<T> => {
  return axios.request({
    url,
    data: params,
    method: 'get',
    params: urlParams(params),
  })
}
export const apiPost = <T = any>(url: any, data = {}, type: ContentType = ContentType.X_WWW_FORM_URLENCODED): Promise<T> => {
  if (type === ContentType.APPLICATION_JSON) {
    data = jsondata(data)
  }
  if (type === ContentType.MULTIPART_FORM_DATA) {
    data = formdata(data)
  }
  if (type === ContentType.X_WWW_FORM_URLENCODED) {
    data = urlParams(data)
  }
  return axios.request({
    url,
    data,
    method: 'post',
    headers: { 'Content-Type': type },
  })
}

/**
 * 参数URLSearchParams格式化
 * @param {object} params
 * @return {object}
 */
export function urlParams(params: Record<string, any>): URLSearchParams {
  const urldata = new URLSearchParams()
  for (const key in params) {
    if (Array.isArray(params[key])) {
      params[key].forEach(e => urldata.append(key, e))
    }
    else {
      urldata.append(key, params[key])
    }
  }
  return urldata
}

/** 参数JSON格式化 */
function jsondata(data: any) {
  return JSON.stringify(data)
}

/**
 * 参数FormData格式化
 * @param {object} data
 * @return {object}
 */
function formdata(data: any) {
  const formdata = new FormData()
  for (const key in data) {
    if (data[key] !== null) { formdata.append(key, data[key]) }
  }
  return formdata
}
